﻿using CodeBackup.Code;
using CodeBackup.FrmGrid;
using libedi.Trans.Model;
using Newtonsoft.Json;
using System.Text;
using System.Windows.Forms;
using static System.Windows.Forms.AxHost;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;


namespace CodeBackup
{
    public partial class FrmMain : Form
    {
        public FrmMain(string[] args)
        {
            if (args.Length > 0)
            {
                libedi.API.Clientbuss.ApiUrl = args[0];
            }
            libedi.API.Clientbuss.ApiUrl = ini.Api;
            CodeConfig.mqtt = new MqttClient();
            CodeConfig.mqtt.ttClient.ApplicationMessageReceivedAsync += TtClient_ApplicationMessageReceivedAsync;
            InitializeComponent();
        }
     
        FGrid grid2;
        //rid grid1;
        private void FrmMain_Load(object sender, EventArgs e)
        {
            libedi.API.Clientbuss.ApiUrl = ini.Api;
            toolStripProgressBar1.Size = new Size(statusStrip1.Width - 20, 25);
            toolStripProgressBar1.Visible = false;  


            grid2 = new FGrid(this, dataGridView2);
            grid2.initGrid(new object[1] { GridType.Grid2 });
            dataGridView2.DataSource = JsonData.Databases();
            //grid1 = new FGrid(this, dataGridView1);
            //grid1.initGrid(new object[1] { GridType.Grid1 });

            var list = JsonData.Databases();
            if (list != null)
            {
                checkedListBox1.Items.AddRange(list.ToArray());
            }
            this.textBox1.Text = ini.SaveDirec;
            this.textBox2.Text = $"{DateTime.Now.ToString("yyyyMMdd")}(代碼).tdb";
            this.checkBox1.Checked = ini.repcode;
            this.KeyDown += FrmMain_KeyDown;
        }

        private void FrmMain_KeyDown(object? sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.F1)
            {
                FrmSet frm=new FrmSet();
                frm.ShowDialog();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {

            List<Database> list = null;


            FrmDatabase frmDatabase = new FrmDatabase((data, n) => { list = data as List<Database>; }, dataGridView2.DataSource as List<Database>);
            frmDatabase.ShowDialog();
            if (list == null) { return; }
            dataGridView2.DataSource = list;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            List<Database> list = dataGridView2.DataSource as List<Database>;
            JsonData.SaveDatabases(list);
            MessageBox.Show("保存成功");
        }

        private void textBox1_DoubleClick(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                ini.SaveDirec = folderBrowserDialog1.SelectedPath;
                this.textBox1.Text = ini.SaveDirec;
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (toolStripProgressBar1.Visible)
            {
                this.richTextBox1.AppendText($"系統正在執行其它任務...{Environment.NewLine}");
                return;
            }


            toolStripProgressBar1.Visible = true;
            var items = this.checkedListBox1.CheckedItems.Cast<Database>().Select(m => m.baseName).ToList();
            //mqtt.BackAsync(items);
            CodeConfig.mqtt.Send("codebackup_back",items);
            this.richTextBox1.AppendText($"正在備份中...{Environment.NewLine}");
            return;

        }

        private Task TtClient_ApplicationMessageReceivedAsync(MQTTnet.Client.MqttApplicationMessageReceivedEventArgs arg)
        {
            // 接收消息时处理
            var message = Encoding.UTF8.GetString(arg.ApplicationMessage.PayloadSegment);
            MqMessage mqttMessage = JsonConvert.DeserializeObject<MqMessage>(message);
            switch (mqttMessage.MethedID)
            {
                case "codebackup_back":
                    {
                        codebackup_back(mqttMessage);
                        break;
                    }
                case "codebackup_reback_tdb":
                case "codebackup_reback_zip":          
                    {
                        codebackup_reback_tdb(mqttMessage);
                        break;
                    }
                default:
                    break;
            }

            return Task.CompletedTask;
        }

        void codebackup_reback_tdb(MqMessage mqttMessage)
        {

            TransMassage tsmessage = JsonConvert.DeserializeObject<TransMassage>(mqttMessage.Message);
            mess(tsmessage.Message);

        }


        void codebackup_back(MqMessage mqttMessage)
        {

            TransMassage tsmessage = JsonConvert.DeserializeObject<TransMassage>(mqttMessage.Message);
            if (tsmessage.transState == TransState.complete)
            {
                DownLoadFile downLoadFile = new DownLoadFile();
                downLoadFile.LoadAsync(tsmessage.Data.ToString(), this.textBox2.Text, (e, s, r) => {

                    this.Invoke(new Action(() =>
                    {
                        toolStripProgressBar1.Visible = false;
                    }));
                    if (s)
                    {
                        mess1($"備份成功！");
                        mess1(e);
                    }
                    else
                    {
                        mess1($"Error：{r}！");
                    }
                });


            }
            else
            {
                mess1(tsmessage.Message);
            }

        }



        private void textBox3_DoubleClick(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {

                this.textBox3.Text = Path.GetFileName(openFileDialog1.FileName);
                this.textBox3.Tag = openFileDialog1.FileName;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {

            if (this.textBox3.Tag == null) return;

            string FilePath = this.textBox3.Tag.ToString();
            UpBackDB upBackDB=new UpBackDB (FilePath);
            upBackDB.UpBack();

        }



        private async void Upload(string FileName)
        {

            Upload upload = new Upload();
            string file = await upload.upAsync(FileName);
            if (!string.IsNullOrEmpty(file))
            {
                var item = JsonConvert.DeserializeObject<Dictionary<string, string>>(file);

                string filename = item["fileName"];
                CodeConfig.mqtt.Send(new MqModel { data = filename, MethedID = "my5", Topic = CodeConfig.mqtt.Topic });
            }
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            ini.repcode = this.checkBox1.Checked;
        }

        void mess(string mess)
        {
            this.Invoke(new Action(() =>
            {
                this.richTextBox2.AppendText($"{mess}{Environment.NewLine}");
            }));
        }

        void mess1(string mess)
        {
            this.Invoke(new Action(() =>
            {
                this.richTextBox1.AppendText($"{mess}{Environment.NewLine}");
            }));
        }

        private void FrmMain_Resize(object sender, EventArgs e)
        {
            toolStripProgressBar1.Size = new Size(statusStrip1.Width - 20, 25);
        }
    }
}
